<?php
$dsn        = 'mysql:dbname=multimedian-wga;host=127.0.0.1';
$user       = 'multimedian-wga';
$password   = 'Kakkerlak';

define( 'MAX_MOVIES', 10 );         //maximum movies to generate
define( 'MAX_ANNOTATIONS', 25 );    //maximum annotations to generate

try{
    $db = new PDO($dsn, $user, $password);
}
catch( PDOException $e ){
    echo 'Connection failed: ' . $e->getMessage();
}

$movie = array(
    'name'          => "Test movie %count",
    'description'   => "This is just some generic data",
    'author'        => "Matthijs van Henten",
    'year'          => date('y-m-d'),
    'filename'      =>  "movie_%count.ogg",
    'published'     => date('Y-m-d h:m:s'),
    'license'       => "CC share-a-like",
    'copyright'     => "2009 Waag Society"
);

$channel_types = array(
    'single-select', 'multi-select', 'multi-open', 'comment' 
);

$channels = array(
    'speakers'  => array( 'Who is talking now?', 1, 0 ),
    'animals'   => array( 'What animal do we see?', 2, 0 ),
    'things'    => array( 'Special things', 3, 0 ),
    'comments'  => array( 'Comments, comments', 4, 1 )
);

$keywords = array(
    'speakers'  => array('Bill Gates', 'Adam Zaretsky', 'Matthijs van Henten', 'Leonardo Da Vinci'),
    'animals'   => array( 'rabbit', 'horse', 'chicken', 'frog', 'crocodile', 'ant' ),
    'things'    => array( 'table', 'chair', 'house', 'knife', 'computer', 'paper' ),
    'comments'  => array()
);

$channelTypes = array(
    1   => 'single-select',
    2   => 'multi-select',
    3   => 'multi-open',
    4   => 'comment',
    5   => 'single-open',
    6   => 'open',
    7   => 'multi-select-comment',
);

$domains = array('science', 'nature', 'technology');

function random_lipsum( $count = 11 ){
    $lipsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec est nisi, molestie egestas metus. Aenean varius, dui a mattis cursus, neque urna hendrerit est, aliquam viverra orci neque eget lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam pellentesque mauris condimentum eros adipiscing lobortis. Aenean eget lorem sit amet nibh facilisis tincidunt sit amet a odio. Suspendisse neque purus, tincidunt vitae malesuada vitae, ullamcorper non urna. Proin adipiscing neque id ligula suscipit condimentum luctus ligula viverra. Maecenas pulvinar consectetur eros eu egestas. Mauris hendrerit nunc eu sapien ornare sodales. Phasellus facilisis aliquet dui, non ultrices augue ultrices a. Morbi sit amet purus est. Aliquam vitae est orci. Donec eu mi in quam sodales accumsan. Donec ac sapien eget augue dignissim pharetra. Vestibulum a vulputate sapien.';
    
    $words = explode( ' ', strtolower($lipsum) );
    shuffle( $words );
    
    $select = array_slice( $words, 0, $count );
    return ucfirst( join( ' ', $select ) );    
}


function add_quote( $value ){
    global $db;
    if( !is_integer( $value ) ){
        $value = $db->quote( $value );
    }
    return $value;
}

function sql_insert( $table, $values, $replace = NULL ){
    global $db;
    
    $keys   = array_keys( $values );
    $values = array_map( 'add_quote', array_values( $values ) );
    
    $query = '
        INSERT INTO ' . $table . '
        (' . join( ',', $keys ) . ')
        VALUES
        (' . join( ',', $values ) . ')
    ';
    
    if( isset( $replace ) && is_array( $replace ) ){
        $query = str_replace( array_keys( $replace ), array_values( $replace ), $query );
    }
    
    $db->query( $query );
    return $db->lastInsertId();    
}

function make_annotation( $movieId, $channelId, $keywords, $time, $duration, $comment = '' ){
    global $db;
    
    $annotation = array(
        'channel_id' => $channelId,
        'movie_id'   => $movieId,
        'duration'   => $duration,
        'time'       => $time,
        'comment'    => $comment
    );
    
    $annotationId = sql_insert( 'annotation', $annotation );
    
    if( count( $keywords ) > 0 ){
        foreach( $keywords as $id => $keyword ){
            sql_insert( 'annotation_keyword', array( 'annotation_id' => $annotationId, 'keyword_id' => $id ) );     
        }    
    }
}

foreach( $channelTypes as $id => $name ){
    sql_insert( 'channel_type', array('name' => $name ) );
}

foreach( $keywords as $domain => $keywords ){
    $domainId = sql_insert( 'domain', array(
        'name'          => $domain,
        'description'   => 'Description for ' . ucfirst( $domain )
        )
    );
    
    foreach( $keywords as $keyword ){
        sql_insert( 'keyword', array(
                'name'      => $keyword,
                'domain_id' => $domainId
            )
        );        
    }
}

foreach( $channels as $name => $properties ){
    $channel = array(
        'name'          => $name,
        'description'   => $properties[0],
        'type_id'       => $properties[1],
        'comment'       => $properties[2]    
    );
    
    sql_insert( 'channel', $channel );
}

function array_key_shuffle( $array ){
    $randomKeys = array_keys($array);
    shuffle( $randomKeys );
    $collect    = array();
    
    foreach( $randomKeys as $key ){
        $collect[$key] = $array[$key];
    }
    
    return $collect;    
}



$qh       = $db->query('SELECT * FROM keyword');
$result   =  $qh->fetchAll( PDO::FETCH_GROUP|PDO::FETCH_OBJ );
$keywords = array_combine( array_keys( $result ), array_map( 'reset', $result ));

foreach( range(1, MAX_MOVIES) as $count ){
    $movieId = sql_insert( 'movie', $movie, array('%count' => $count ) );
    
    $qh = $db->query('SELECT * FROM channel');
    
    $result  = $qh->fetchAll( PDO::FETCH_GROUP|PDO::FETCH_OBJ );
    $channels = array_combine( array_keys( $result ) , array_map( 'reset', $result ) );
    
    foreach( $channels as $channelId => $channel ){
        sql_insert( 'channel_movie', array('movie_id' => $movieId, 'channel_id' => $channelId ) );
        $keywords = array_key_shuffle( $keywords );
            
        $collect = array_slice( $keywords , 0, rand(1, 10), true );
        
        foreach( $collect as $keywordId => $keyword ){
            sql_insert( 'channel_keyword', array('channel_id' => $channelId, 'keyword_id' => $keywordId ) );
        }
        
        foreach( range(1, MAX_ANNOTATIONS) as $index ){
            //shuffle( $collect );
            $collect    = array_key_shuffle( $collect );
            $duration   = rand(1, 25);
            $timecode   = rand(25, 600);
            $selection  = array();
            $comment    = '';
            
            switch( $channel->type_id ){
                case 1:
                    $selection = array_slice( $collect, 0, 1, true );
                    break;
                case 2:
                case 3:
                    $selection = array_slice( $collect, 0, rand(1, count($collect)), true );
                    break;
                case 4:
                    $comment = random_lipsum( rand(1, 10) );
                    break;
            }
            
            make_annotation( $movieId, $channelId, $selection, $timecode, $duration, $comment );
        }        
    }    
}





